<!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html lang="cmn-Hans">

<head>
  <title>用户列表</title>
  {{template "admin/partials/html-head.html" .}}
</head>

<body class="hold-transition skin-blue sidebar-mini">
  <div class="wrapper">

    <!-- Main Header -->
    {{template "admin/partials/html-header.html" .}}
    <!-- Left side column. contains the logo and sidebar -->
    {{template "admin/partials/html-menu.html" .}}

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <section class="content-header">
        <h1>
          用户列表
        </h1>
        <ol class="breadcrumb">
          <li><a href="/admin/page/welcome"><i class="fa fa-dashboard"></i>首页</a></li>
          <li class="active">用户列表</li>
        </ol>
      </section>

      <!-- Main content -->
      <section class="content">
        <div class="row">
          <div class="col-xs-12">
            <div class="box">
              <!-- .box-header search-->
              <div class="box-header">
                <div class="search-box">
                  <form class="form-inline" onsubmit="return false">
                    <div class="form-group">
                      <label for="username">name:</label>
                      <input type="text" class="form-control" name="username" placeholder="">
                    </div>
                    <div class="form-group">
                      <label for="mobile">mobile:</label>
                      <input type="text" class="form-control" name="mobile" placeholder="">
                    </div>
                    <div class="form-group">
                      <label for="exampleInputEmail2">email:</label>
                      <input type="email" class="form-control" name="email" placeholder="">
                    </div>
                    <button type="submit" id="search" class="btn btn-default">搜索</button>
                  </form>
                </div>
              </div>
              <!-- /.box-header search-->
              <div class="box-body">
                <table id="dataList" class="table table-bordered table-striped">
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>name</th>
                      <th>gender</th>
                      <th>mobile</th>
                      <th>email</th>
                      <th>address</th>
                      <th>status</th>
                      <th>description</th>
                      <th>createdAt</th>
                      <th>updatedAt</th>
                      <th width="120px">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {{/*<tr>
                      <td></td>
                    </tr>*/}}
                  </tbody>
                  <tfoot>
                    <tr>
                      <th>ID</th>
                      <th>name</th>
                      <th>gender</th>
                      <th>mobile</th>
                      <th>email</th>
                      <th>address</th>
                      <th>status</th>
                      <th>description</th>
                      <th>createdAt</th>
                      <th>updatedAt</th>
                      <th>操作</th>
                    </tr>
                  </tfoot>
                </table>
              </div>
              <!-- /.box-body -->
            </div>
            <!-- /.box -->
          </div>
          <!-- /.col -->
        </div>
        <!-- /.row -->
      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <!-- Main Footer -->
    {{template "admin/partials/html-footer.html"}}

    <!-- Control Sidebar -->
    {{template "admin/partials/html-control-sidebar.html"}}
    <!-- /.Control-sidebar -->
  </div>
  <!-- ./wrapper -->

  <!-- 弹窗内容-->
  <div id="update-dialog" style="display: none;">
    <div class="col-md-12">
      <!-- general form elements -->
      <div class="box box-primary">
        <div class="box-header with-border">
          <h3 class="box-title">修改用户</h3>
        </div>
        <!-- /.box-header -->
        <!-- form start -->
        <form role="form" method="post" onsubmit="return false">
          <input type="hidden" name="userId">
          <div class="box-body">
            <div class="form-group">
              <label for="name">name</label>
              <input type="text" class="form-control" name="username" placeholder="username">
            </div>
            <div class="form-group">
              <label for="gender">gender</label>
              <select name="gender" class="form-control">
                <option value="0">女</option>
                <option value="1">男</option>
              </select>
            </div>
            <div class="form-group">
              <label for="mobile">mobile</label>
              <input type="text" class="form-control" name="mobile" placeholder="mobile" disabled>
            </div>
            <div class="form-group">
              <label for="email">email</label>
              <input type="text" class="form-control" name="email" placeholder="email">
            </div>
            <div class="form-group">
              <label for="address">address</label>
              <input type="text" class="form-control" name="addr" placeholder="addr">
            </div>
            <div class="form-group">
              <label for="description">description</label>
              <input type="text" class="form-control" name="desc" placeholder="description">
            </div>
          </div>
          <!-- /.box-body 使用layer的回调执行提交
                <div class="box-footer">
                  <input type="hidden" id="userId">
                  <button type="submit" class="btn btn-primary J-submit">Submit</button>
                </div>
                -->
        </form>
      </div>
      <!-- /.box -->
    </div>
  </div>
  <!-- 加权限 -->
  <div id="permission-dialog" style="display: none;">
    <div class="col-md-12">
      <!-- general form elements -->
      <div class="box box-primary">
        <div class="box-header with-border">
          <h3 class="box-title">编辑权限</h3>
        </div>
        <!-- /.box-header -->
        <!-- form start -->
        <form role="form" method="post" onsubmit="return false">
          <input type="hidden" id="userId">
          <div class="box-body">
            <div class="form-group">
              <div class="checkbox" id="perssions">

              </div>
            </div>
          </div>
        </form>
      </div>
      <!-- /.box -->
    </div>
  </div>
  <!-- /弹窗内容-->

  <!-- REQUIRED JS SCRIPTS -->
  {{template "admin/partials/html-js.html"}}
  <!-- /REQUIRED JS SCRIPTS -->

  <!-- page script -->
  <script type="text/javascript">
    $(function () {
      //列表
      var dataList = $('#dataList').DataTable({
        language: {
          processing: "数据加载中……",
          zeroRecords: "No records to display"
        },
        paging: true,
        lengthChange: false,
        searching: false,
        ordering: true,
        info: true,
        scrollX: true,
        autoWidth: true,
        serverSide: true,
        processing: true,
        ajax: function (data, callback, settings) {
          var postData = {
            draw: data.draw,
            perPage: data.length,
            start: data.start,
          };
          if ($(".search-box input[name=username]").val()) {
            postData.username = $(".search-box input[name=username]").val();
          }
          if ($(".search-box input[name=mobile]").val()) {
            postData.mobile = $(".search-box input[name=mobile]").val();
          }
          if ($(".search-box input[name=email]").val()) {
            postData.email = $(".search-box input[name=email]").val();
          }
          $.ajax({
            url: '/admin/api/users',
            type: 'GET', //GET
            data: postData,
            timeout: 5000,    //超时时间
            dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr, a, b) {
              console.log('发送前')
            },
            success: function (res, textStatus, jqXHR) {
              if (res.code == 1) {
                layer.msg(res.msg, { icon: 5 });
                return
              }
              var dtData = {
                recordsTotal: res.data.total || 0,
                recordsFiltered: res.data.total || 0,
                data: res.data.result || [],
                draw: res.data.draw || 0
              };
              callback(dtData);
            },
            error: function (xhr, textStatus) {
              console.log('错误')
            },
            complete: function () {
              console.log('结束')
            }
          })
        },
        rowId: 'id',//自动设置行id
        columns: [
          { data: 'id' },
          { data: 'username' },
          { data: 'gender' },
          { data: 'mobile', "searchable": true, },
          { data: 'email' },
          { data: 'addr' },
          {
            data: 'status',
            render: function (data, type, row) {
              var html = '<span class="label label-primary">未知</span>';
              if (data == 0) {
                html = '<span class="label label-danger">禁用</span>';
              } else {
                html = '<span class="label label-success">启用</span>';
              }
              return html;
            }
          },
          { data: 'description' },
          { data: 'created_at' },
          { data: 'updated_at' },
          {
            data: 'mobile',
            render: function (data, type, row) {
              var html = '<a href="javascript:void(0);" class="J-update">编辑</a>&nbsp;'
              if (row.status == 1) {
                html += '<a href="javascript:void(0);" class="J-disable">禁用</a>&nbsp;'
              } else {
                html += '<a href="javascript:void(0);" class="J-enable">启用</a>&nbsp;'
              }
              html += '<a href="javascript:void(0);" class="J-permission">权限</a>'
              return html;
            }
          }
        ],
        "createdRow": function (row, data, dataIndex) {
          //有了DT_RowId属性就会自动添加id到行上,不需要在此操作，可以做其他事
          $(row).data("userName", data.userName);
        }
      });
      //禁用
      $("#dataList").on("click", ".J-disable", function () {
        var id = $(this).closest("tr").attr("id");
        if (confirm("禁用后不可登录，确定？")) {
          $.ajax({
            url: '/admin/api/user/' + id + '/status',
            type: 'put', //GET
            async: true,    //或false,是否异步
            data: {
              userId: id,
              status: 0
            },
            timeout: 5000,    //超时时间
            dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr) {
              console.log('发送前')
            },
            success: function (data, textStatus, jqXHR) {
              if (data.code !== 0) {
                layer.msg(data.msg, { icon: 5 });
                return
              }
              layer.msg("操作成功！", { icon: 6 });
              dataList.ajax.reload();
            },
            error: function (xhr, textStatus) {
              console.log('错误')
            },
            complete: function () {
              console.log('结束')
            }
          })
        }
      });
      //启用
      $("#dataList").on("click", ".J-enable", function () {
        var id = $(this).closest("tr").attr("id");
        if (confirm("确定启用？")) {
          $.ajax({
            url: '/admin/api/user/' + id + '/status',
            type: 'put', //GET
            async: true,    //或false,是否异步
            data: {
              userId: id,
              status: 1
            },
            timeout: 5000,    //超时时间
            dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
            beforeSend: function (xhr) {
              console.log('发送前')
            },
            success: function (data, textStatus, jqXHR) {
              if (data.code !== 0) {
                layer.msg(data.msg, { icon: 5 });
                return
              }
              layer.msg("操作成功！", { icon: 6 });
              dataList.ajax.reload();
            },
            error: function (xhr, textStatus) {
              console.log('错误')
            },
            complete: function () {
              console.log('结束')
            }
          })
        }
      });
      //修改
      $("#dataList").on("click", ".J-update", function () {
        var id = $(this).closest("tr").attr("id");
        $.get("/admin/api/user/" + id, function (data) {
          if (data.code !== 0) {
            layer.msg(data.msg, { icon: 5 });
            return
          }
          let $updatedialog = $("#update-dialog");
          $updatedialog.find("input[name=userId]").val(id);
          $updatedialog.find("input[name=username]").val(data.data.username);
          $updatedialog.find("select[name=gender]").val(data.data.gender);
          $updatedialog.find("input[name=email]").val(data.data.email);
          $updatedialog.find("input[name=mobile]").val(data.data.mobile);
          $updatedialog.find("input[name=addr]").val(data.data.addr);
          $updatedialog.find("input[name=desc]").val(data.data.description);
          layer.open({
            type: 1,
            area: ['500px', 'auto'],
            btn: ['确定', '取消'],
            fixed: false,//跟随滚动
            shadeClose: true, //点击遮罩关闭
            content: $("#update-dialog"),
            yes: function (index, layero) {
              let params = $updatedialog.find("form").serializeArray();
              var values = {};
              for (x in params) {
                values[params[x].name] = params[x].value;
              }
              values.userId = Number(values.userId);
              var idata = JSON.stringify(values)
              console.log(idata);
              $.ajax({
                url: '/admin/api/user',
                type: 'PUT', //GET
                async: true,    //或false,是否异步
                contentType: 'application/json',
                data: idata,
                timeout: 5000,    //超时时间
                dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                success: function (data, textStatus, jqXHR) {
                  if (data.code !== 0) {
                    layer.msg(data.msg, { icon: 5 });
                    return
                  }
                  layer.msg("修改成功！", { icon: 6 });
                  layer.close(index); //如果设定了yes回调，需进行手工关闭
                  dataList.ajax.reload();
                },
                error: function (xhr, textStatus) {
                  layer.msg("修改失败！", { icon: 5 });
                },
                complete: function () {

                }
              })
            }, btn2: function (index, layero) {
              layer.close(index);
            }
          });
        })
      });
      //权限
      $("#dataList").on("click", ".J-permission", function () {
        var userId = $(this).closest("tr").attr("id");
        var userName = $(this).closest("tr").data("username");
        $.get("/admin/api/user-roles/" + userId, function (data) {
          if (data.code !== 0) {
            layer.msg(data.msg, { icon: 5 });
            return
          }
          var ps = "";
          data.data.forEach(function (item, index) {
            ps += '<label class="checkbox-inline">'
            ps += '<input type="checkbox" name="role" value="' + item.roleId + '" ' + (item.checked ? 'checked=\"checked\"' : '\"\"') + ' />'
            ps += item.description + '</label>'
          });
          $("#perssions").html(ps);
          layer.open({
            type: 1,
            area: ['500px', 'auto'],
            btn: ['确定', '取消'],
            fixed: false,//跟随滚动
            shadeClose: true, //点击遮罩关闭
            content: $("#permission-dialog"),
            yes: function (index, layero) {
              console.log($("input[name=role]:checked").val());
              var roles = [];
              $("input[name=role]:checked").each(function (i, n) {
                roles[i] = parseInt($(this).val());
              });
              $.ajax({
                url: '/admin/api/user/add-roles',
                type: 'POST',
                contentType: 'application/json',
                async: true,    //或false,是否异步
                data: JSON.stringify({
                  userId: parseInt(userId),
                  roles: roles
                }),
                timeout: 5000,    //超时时间
                dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                success: function (data, textStatus, jqXHR) {
                  if (data.code !== 0) {
                    layer.msg(data.msg, { icon: 5 });
                    return
                  }
                  layer.msg("修改成功！", { icon: 6 });
                  layer.close(index); //如果设定了yes回调，需进行手工关闭
                  dataList.ajax.reload();
                },
                error: function (xhr, textStatus) {
                  layer.msg("修改失败！", { icon: 5 });
                },
                complete: function () {

                }
              })
            }, btn2: function (index, layero) {
              layer.close(index);
            }
          });
        })
      });
      $("#search").on('click', function () {
        dataList.ajax.reload();//( "sg" ).draw();
      })
    })
  </script>
</body>

</html>